package com.business.file.service;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class ImagesService {


    private Logger logger = LoggerFactory.getLogger(ImagesService.class);

    /**
     * 重新设置图片大小和质量
     *
     * @param resourcesPath
     */
    public void resizedImage(String resourcesPath) {
        try {
            String resizedPath = resourcesPath.replaceAll("/images/", "/images-resized/");
            String modulePath = resizedPath.substring(0, resizedPath.lastIndexOf("/"));
            File moduleFile = new File(modulePath);
            if (!moduleFile.exists()) {
                moduleFile.mkdirs();
            }
            File resizedFile = new File(resizedPath);
            resizedFile.createNewFile();
            Thumbnails.Builder builder = Thumbnails.of(resourcesPath);
            if (modulePath.contains("-head/")) {//头像
                builder.width(150).height(150).toFile(resizedFile);
            } else if (modulePath.contains("dynamic-images")) {//动态图片
                builder.scale(0.4).outputQuality(0.7).toFile(resizedFile);
            } else {
                builder.scale(0.5).outputQuality(0.8).toFile(resizedFile);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
